package io.kiki.stack.http.feign.SpringMvcContract.annotation;

import io.kiki.stack.http.feign.MethodMetadata;
import io.kiki.stack.http.feign.SpringMvcContract.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

import static io.kiki.stack.http.feign.Util.checkState;
import static io.kiki.stack.http.feign.Util.emptyToNull;

/**
 * {@link RequestParam} parameter processor.
 *
 * @see AnnotatedParameterProcessor
 */
public class RequestParamParameterProcessor implements AnnotatedParameterProcessor {

    private static final Class<RequestParam> ANNOTATION = RequestParam.class;

    @Override
    public Class<? extends Annotation> getAnnotationType() {
        return ANNOTATION;
    }

    @Override
    public boolean processArgument(AnnotatedParameterContext annotatedParameterContext, Annotation annotation, Method method) {
        int parameterIndex = annotatedParameterContext.getParameterIndex();
        Class<?> parameterType = method.getParameterTypes()[parameterIndex];
        MethodMetadata data = annotatedParameterContext.getMethodMetadata();

        if (Map.class.isAssignableFrom(parameterType)) {
            checkState(data.queryMapIndex() == null, "Query map can only be present once.");
            data.queryMapIndex(parameterIndex);

            return true;
        }

        RequestParam requestParam = ANNOTATION.cast(annotation);
        String name = requestParam.value();
        checkState(emptyToNull(name) != null, "RequestParam.value() was empty on parameter %s of method %s", parameterIndex, method.getName());
        annotatedParameterContext.setParameterName(name);

        Collection<String> query = annotatedParameterContext.setTemplateParameter(name, data.template().queries().get(name));
        data.template().query(name, query);
        return true;
    }

}
